package com.common;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpUtils {

	public static String sendPost(String data, String url, HashMap<String, String> headerMap) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);// 创建httpPost
		for (Map.Entry<String, String> entry : headerMap.entrySet()) {
			httpPost.setHeader(entry.getKey(), entry.getValue());
		}
		String charSet = "UTF-8";
		StringEntity entity = new StringEntity(data, charSet);
		httpPost.setEntity(entity);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(100000)
				.setConnectionRequestTimeout(100000).setSocketTimeout(100000).build();// 设置请求和传输超时时间
		httpPost.setConfig(requestConfig);
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httpPost);
			StatusLine status = response.getStatusLine();
			int state = status.getStatusCode();
			if (state == HttpStatus.SC_OK || state == HttpStatus.SC_ACCEPTED) {
				HttpEntity responseEntity = response.getEntity();
				String jsonString = EntityUtils.toString(responseEntity, "UTF-8");
				return jsonString;
			} else {
				return "error";
			}
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
			return "SocketTimeout";
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpPost.releaseConnection();
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}
